package com.project.lx.gettxtfilename;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取手机txt文件
 */
public class GetFileActivity extends AppCompatActivity {

    private ListView file_list;
    private List<ItemBean> name;
    ListAdapter adapter;

    ProgressDialog progressDialog;
    //动态获取权限监听
    private static PermissionListener mListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_file);

        file_list = (ListView) findViewById(R.id.file_list);
        name = new ArrayList();

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("加载中。。。");
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
        getPermission();
    }

    /**
     * 动态获取权限
     */
    public void getPermission() {
        //获取读写权限
        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        requestRuntimePermission(permissions, new PermissionListener() {
            @Override
            public void onGranted() {
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    File path = Environment.getExternalStorageDirectory();// 获得本机存储路径
                    final File[] files = path.listFiles();// 读取
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            getFileName(files);
                            handler.sendEmptyMessage(0);
                        }
                    }).start();

                }


//                adapter.notifyDataSetChanged();

                for (int i = 0; i < name.size(); i++) {
                    Log.i("liu", "list.  name:  " + name.get(i).getFileName().toString());
                }
                Log.i("all", "共有多少个文件 " + name.size());
            }

            @Override
            public void onDenied(List<String> deniedPermission) {

            }
        });
    }

    //andrpoid 6.0 需要写运行时权限
    public void requestRuntimePermission(String[] permissions, PermissionListener listener) {

        mListener = listener;
        List<String> permissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }
        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionList.toArray(new String[permissionList.size()]), 1);
        } else {
            mListener.onGranted();
        }
    }

    public interface PermissionListener {

        /**
         * 成功获取权限
         */
        void onGranted();

        /**
         * 为获取权限
         *
         * @param deniedPermission
         */
        void onDenied(List<String> deniedPermission);

    }

    int content = 1;

    /**
     * 递归获取文件列表
     * @param files
     */
    private void getFileName(File[] files) {
        if (files != null) {// 先判断目录是否为空，否则会报空指针
            for (File file : files) {
                if (file.isDirectory()) {
                    Log.i("zeng", "若是文件目录。继续读1" + file.getName().toString()
                            + file.getPath().toString());

                    getFileName(file.listFiles());
                } else {
                    String fileName = file.getName();
                    if (fileName.endsWith(".txt")) {
//                        HashMap map = new HashMap();
                        ItemBean itemBean = new ItemBean();
                        String s = fileName.substring(0, fileName.lastIndexOf(".")).toString() + ".txt"  + "    编号 ： " + content;
                        Log.i("zeng", "文件名txt：：   " + s);
                        Log.i("lujing", "文件路径:   " + file.getPath());
//                        map.put("Name", s);
                        itemBean.setFileName(s);
                        itemBean.setFilePath(file.getPath());
                        name.add(itemBean);

                        content++;
                    }
                }
            }
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    progressDialog.dismiss();
                    adapter = new ListAdapter(GetFileActivity.this, name);
                    file_list.setAdapter(adapter);
                    file_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Log.i("dayin", "路径: " + name.get(position).getFilePath().toString());
                            File file = new File(name.get(position).getFilePath());
                            Uri uri;
                            // 判断手机系统版本号
                            if (Build.VERSION.SDK_INT >= 24) {
                                // 7.0及以上系统使用这个方法处理图片
                                uri =  FileProvider.getUriForFile(getApplicationContext(), "com.project.lx.gettxtfilename.fileprovider", file);
                            } else {
                                uri = Uri.fromFile(file);
                            }

                            Intent intent = new Intent("android.intent.action.VIEW");
                            intent.addCategory("android.intent.category.DEFAULT");
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            intent.setDataAndType(uri, "text/plain");
                            startActivity(intent);
                        }
                    });
                    break;
            }
        }
    };

}
